﻿using System;
using System.Linq;
using System.Data.Entity;
using System.Web.Mvc;
using VOD.Models;
using PagedList;

namespace VOD.Controllers
{
    public class SearchController : Controller
    {
        private readonly VODEntities _db = new VODEntities();
        //
        // GET: /Search/

        public ActionResult Index(string videoName,int? page)
        {
            var videos = _db.Videos
                        .Include(v=>v.VideoAndTypes)
                        .OrderByDescending(v=>v.UpdateDate).ToList();
            if (!String.IsNullOrEmpty(videoName))
            {
                videos = videos.Where(v => v.Name.ToUpper().Contains(videoName)).ToList();
            }
            ViewBag.Page = page ?? 1;
            //分页，使用PageList
            int pageSize = 10;//定义每页显示的记录数
            int pageIndex = (page ?? 1) - 1;
            return View(videos.ToPagedList(pageIndex,pageSize));
        }

        public ActionResult VideoList(string areaID, int? typeID,int? year,int? page,int categoryID)
        {
            var videos = _db.Videos
                        .Include(v => v.VideoAndTypes)
                        .Where(v=>v.CategoryID==categoryID)
                        .OrderByDescending(v => v.UpdateDate).ToList();
            if (areaID!=null)
            {
                videos = videos.Where(v => v.VideoArea.AreaName==areaID).ToList();
                ViewBag.TopTitle = areaID;
            }
            if (typeID != null)
            {
                videos = videos.Where(v => v.VideoAndTypes.Any(t => t.TypeID == typeID)).ToList();
                ViewBag.TopTitle = _db.VideoTypes.Find(typeID).TypeName;
            }
            if (year != null)
            {
                videos = videos.Where(v => v.ShowYear == year.ToString()).ToList();
                ViewBag.TopTitle = year;
            }
            ViewBag.CategoryName = _db.VideoCategories.Find(categoryID).CategoryName;
            ViewBag.Page = page ?? 1;
            //分页，使用PageList
            int pageSize = 20;//定义每页显示的记录数
            int pageIndex = (page ?? 1) - 1;
            return View(videos.ToPagedList(pageIndex, pageSize));
        }

        //搜索框AutoComplete
        public ActionResult Quick(string term)
        {
            var videos = _db.Videos
                .OrderBy(v => v.UpdateDate)
                .Select(r => new { label = r.Name });
            if (term != null)
            {
                videos = videos.Where(v => v.label.Contains(term));
            }
            return Json(videos.Take(10), JsonRequestBehavior.AllowGet);
        }

        protected override void Dispose(bool disposing)
        {
            _db.Dispose();
            base.Dispose(disposing);
        }
    }
}
